import type { LoginCredentials, RegisterCredentials, WxLoginCredentials } from '@/api/auth'
import type { UserInfo } from '@/types/user'
import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
import { login as apiLogin, logout as apiLogout, register as apiRegister, wxLogin as apiWxLogin } from '@/api/auth'
import { WechatErrorHandler } from '@/utils/wechat-error-handler'

export const useUserStore = defineStore('user', () => {
  // 状态定义
  const userInfo = ref<UserInfo | null>(uni.getStorageSync('userInfo') || null)
  const token = ref<string>(uni.getStorageSync('token') || '')
  const isLoggedIn = computed(() => !!token.value)

  // 用户登录
  const login = async (credentials: LoginCredentials) => {
    try {
      const result = await apiLogin(credentials)
      const response = result.data // 从CommonResult中提取data

      // 构建用户信息
      const user: UserInfo = {
        id: response.userInfo.id.toString(),
        username: response.userInfo.username,
        nickname: response.userInfo.nickname || response.userInfo.username,
        avatar: response.userInfo.avatar || '/static/images/default-avatar.png',
        // phone: response.userInfo.phone || '', // 注释掉手机号存储
        email: response.userInfo.email || '',
        vipExpire: '2025-12-31', // 默认VIP过期时间
      }

      // 更新状态
      userInfo.value = user
      token.value = response.accessToken

      // 保存到本地存储
      uni.setStorageSync('userInfo', user)
      uni.setStorageSync('token', response.accessToken)

      return {
        userInfo: user,
        token: response.accessToken,
      }
    }
    catch (error: any) {
      throw new Error(error.message || '登录失败')
    }
  }

  // 微信登录方法
  const wxLogin = async (wxData: WxLoginCredentials) => {
    try {
      console.log('开始微信登录，数据:', {
        hasCode: !!wxData.code,
        codeLength: wxData.code?.length,
        hasUserInfo: !!wxData.userInfo,
        userNickname: wxData.userInfo?.nickName,
      })

      console.log('调用微信登录API...')
      const result = await apiWxLogin(wxData)
      console.log('API调用成功，原始响应:', result)

      const response = result.data // 从CommonResult中提取data
      console.log('提取的响应数据:', response)

      // 验证响应数据
      if (!response || !response.userInfo) {
        throw new Error('登录响应数据格式错误')
      }

      // 构建用户信息
      const user: UserInfo = {
        id: response.userInfo.id.toString(),
        username: response.userInfo.username,
        nickname: response.userInfo.nickname || response.userInfo.username,
        avatar: response.userInfo.avatar || '/static/images/default-avatar.png',
        // phone: response.userInfo.phone || '', // 注释掉手机号存储
        email: response.userInfo.email || '',
        vipExpire: '2025-12-31', // 默认VIP过期时间
      }

      // 更新状态
      userInfo.value = user
      token.value = response.accessToken

      // 保存到本地存储
      uni.setStorageSync('userInfo', user)
      uni.setStorageSync('token', response.accessToken)

      // 保存微信openid（如果有）
      if (response.openid) {
        uni.setStorageSync('wechat_openid', response.openid)
        console.log('保存微信openid:', response.openid)
      }

      console.log('微信登录成功，用户信息:', user)

      return {
        userInfo: user,
        token: response.accessToken,
        openid: response.openid,
      }
    }
    catch (error: any) {
      console.error('微信登录失败，完整错误信息:', error)
      console.error('错误类型:', typeof error)
      console.error('错误消息:', error?.message)
      console.error('错误响应:', error?.response)
      console.error('错误状态码:', error?.response?.status)
      console.error('错误数据:', error?.response?.data)

      // 使用统一的错误处理器
      const errorMessage = WechatErrorHandler.handleError(error, 'backend-api')
      console.error('处理后的错误消息:', errorMessage)
      throw new Error(errorMessage)
    }
  }

  // 用户注册
  const register = async (credentials: RegisterCredentials) => {
    try {
      const result = await apiRegister(credentials)
      const response = result.data // 从CommonResult中提取data

      // 构建用户信息
      const user: UserInfo = {
        id: response.userInfo.id.toString(),
        username: response.userInfo.username,
        nickname: response.userInfo.nickname || response.userInfo.username,
        avatar: response.userInfo.avatar || '/static/images/default-avatar.png',
        // phone: response.userInfo.phone || '', // 注释掉手机号存储
        email: response.userInfo.email || '',
        vipExpire: '2025-12-31', // 默认VIP过期时间
      }

      // 更新状态
      userInfo.value = user
      token.value = response.accessToken

      // 保存到本地存储
      uni.setStorageSync('userInfo', user)
      uni.setStorageSync('token', response.accessToken)

      return {
        userInfo: user,
        token: response.accessToken,
      }
    }
    catch (error: any) {
      throw new Error(error.message || '注册失败')
    }
  }

  // 退出登录
  const logout = async () => {
    try {
      if (token.value) {
        await apiLogout()
      }
    }
    catch (error) {
      console.warn('退出登录API调用失败:', error)
    }
    finally {
      // 无论API调用是否成功，都清除本地状态
      userInfo.value = null
      token.value = ''
      uni.removeStorageSync('userInfo')
      uni.removeStorageSync('token')
    }
  }

  return {
    userInfo,
    token,
    isLoggedIn,
    login,
    register,
    wxLogin,
    logout,
  }
}, {
  persist: {
    key: 'user-store',
    paths: ['userInfo', 'token'],
    storage: {
      getItem: key => uni.getStorageSync(key),
      setItem: (key, value) => uni.setStorageSync(key, value),
      removeItem: key => uni.removeStorageSync(key),
    },
  },
})
